// 计算每个sku后面有多少项
export function getLevels(tree) {
	let level = [];
	for(let i = tree.length - 1; i >= 0; i--) {
		if(tree[i + 1] && tree[i + 1].sku_values) {
			level[i] = tree[i + 1].sku_values.length * level[i + 1] || 1;
		} else {
			level[i] = 1;
		}
	}
	return level;
}

/**
 * 笛卡尔积运算
 * @param  {[type]} tree   [description]
 * @param  {Array}  stocks [description]
 * @return {[type]}        [description]
 */
export function flatten(tree, stocks = [], options) {
	let {
		optionValue = 'id', optionText = 'prop_name', propValue = 'id', propText = 'value', imgValue = 'imgUrl'
	} = options || {};
	let result = [];
	let skuLen = 0;
	let stockMap = {}; // 记录已存在的stock的数据
	const level = getLevels(tree);
	if(tree.length === 0) return result;
	tree.forEach(sku => {
		const {
			sku_values
		} = sku;
		if(!sku_values || sku_values.length === 0) return true;
		skuLen = (skuLen || 1) * sku_values.length;
	});
	// 根据已有的stocks生成一个map
	stocks.forEach(stock => {
		let {
			skus,
			...attr
		} = stock;
		stockMap[skus.map(item => `${item.pid}_${item.vid}`).join('|')] = attr;
	});
	
	
	for(let i = 0; i < skuLen; i++) {
		let skus = [];
		let mapKey = [];
		//组合规格图片
		let image = ''
		tree.forEach((sku, column) => {
			const {
				sku_values
			} = sku;
			let item = {};
			if(!sku_values || sku_values.length === 0) return true;
			if(sku_values.length > 1) {
				let row = parseInt(i / level[column], 10) % sku_values.length;
				item = tree[column].sku_values[row];
			} else {
				item = tree[column].sku_values[0];
			}
			if(!sku[optionValue] || !item[propValue]) return;
			mapKey.push(`${sku[optionValue]}_${item[propValue]}`);
			skus.push({
				pid: sku[optionValue],
				p: sku[optionText],
				vid: item[propValue],
				v: item[propText],
			});

			item[imgValue] ? image = item[imgValue] : ''
		});

		let { ...data
		} = stockMap[mapKey.join('|')] || {
			stock: "",
			supplier_price: "",
			spu_no: "",
			sku_no: "",
			sale_price: ""
		};
		// 从map中找出存在的sku并保留其值
		result.push({ ...data,
			image,
			skus
		});
	}

	return result;
}